/**
 * 
 */
package org.vsg.security.web;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.jsecurity.authc.AuthenticationException;
import org.jsecurity.authc.Authenticator;
import org.jsecurity.authc.UnknownAccountException;
import org.jsecurity.authc.UsernamePasswordToken;
import org.jsecurity.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.vsg.common.web.json.SubmitResult;
import org.vsg.security.json.AccountVali;

/**
 * @author Bill Vison
 *
 */
@Controller
public class ApplicationController {

	/**
	 * set the logger for develope code , do not use System.print(ln) to out print message.
	 */
	private static final Logger logger = LoggerFactory.getLogger(ApplicationController.class);
	
	
	@Resource(name="securityManager")
	private Authenticator authenticator;


	@RequestMapping("/login.do")
	public String loginEntry(HttpServletRequest req , HttpServletResponse res) throws Exception {
		// TODO Auto-generated method stub
		String userName = req.getParameter("j_username");
		String password = req.getParameter("j_password");
		
		
		if (userName == null) {
			// --- throw user name is null exception ---
		}

		logger.info("Login username is " + userName);
		

		UsernamePasswordToken token = new UsernamePasswordToken(userName,	password);
		try {
			//authenticator.login(token);
		
		} catch (AuthenticationException e) {
			if (logger.isDebugEnabled()) {
				logger.debug("Error authenticating.", e);
			}
		}
		
		
		Session accountSession = null;

		
		// ---- response to client ----
		SubmitResult submitResult = new SubmitResult();
		
		// --- server ok ---
		submitResult.setSuccess(true);		
	
		AccountVali account = new AccountVali();
		account.setSession( req.getSession().getId() );
		// --- entry url ---
		account.setMainpage("index.htm");

		
		submitResult.setData( account );

		JSONObject jsonObject = JSONObject.fromObject(submitResult ); 
		
		req.setAttribute("json", jsonObject);		
		
		logger.info(jsonObject.toString());
		
		return "result";
	}
	
	/**
	 * handle desktoLoginEntry()
	 */
	@RequestMapping("/saasAuthenticate.do")
	public String saasFrameworkLoginEntry(HttpServletRequest req , HttpServletResponse res) throws Exception {
		// TODO Auto-generated method stub
		String userName = req.getParameter("username");
		String password = req.getParameter("password");
		
		
		if (userName == null) {
			// --- throw user name is null exception ---
		}

		logger.info("Login username is " + userName);

		UsernamePasswordToken token = new UsernamePasswordToken(userName,	password);

		// ---- response to client ----
		SubmitResult submitResult = new SubmitResult();
		
		try {
			authenticator.authenticate(token);

			// --- server ok ---
			submitResult.setSuccess(true);
			submitResult.setMsg("登陆成功!");
		
			AccountVali account = new AccountVali();
			account.setSession( req.getSession().getId() );
			// --- entry url ---
			account.setMainpage("index.htm");

			
			submitResult.setData( account );			
			
		} catch (UnknownAccountException uae) {
			
			submitResult.setSuccess(false);
			submitResult.setErrorMessage("该帐户不存在，请重新输入正常的帐号");
			
			logger.debug( uae.getLocalizedMessage() );
			
		} catch (AuthenticationException e) {
			if (logger.isDebugEnabled()) {
				logger.debug("Error authenticating.", e);
			}
		}
		

		JSONObject jsonObject = JSONObject.fromObject(submitResult ); 
		
		req.setAttribute("json", jsonObject);		
		
		logger.info(jsonObject.toString());
		
		return "result";
	}	
}
